package ipsite.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.Cache;

import ipsite.data.Data;
import ipsite.data.Memcache;
import ipsite.server.AgeDomain;
import ipsite.server.AlexaUpdate;
import ipsite.server.GetPage;
import ipsite.server.GetTrackIp;
import ipsite.server.GooglePageRank;
import ipsite.server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@SuppressWarnings("serial")
public class SearchDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String name = Utils.fomatDomain(URLDecoder.decode(req.getParameter("name"),"UTF-8"));
		
		if(Utils.checkDomain(name))
		{
			DBCollection coll = Data.data("domain");
			
			DBObject domains = coll.findOne(new BasicDBObject("name",name));
			
			if(domains == null)
			{
				Random generator = new Random();
				int r = generator.nextInt(100000);
				DBObject domain = new BasicDBObject();
				domain.put("name", name);
				domain.put("update", new Date().getTime());
				domain.put("random", r);

				try {
					new GetPage(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GooglePageRank(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AgeDomain(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AlexaUpdate(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new Whois(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GetTrackIp(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					Thread.sleep(10000);
					coll.save(domain);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Memcache.setMemcache("last-update", domain.get("name").toString());
				
				resp.sendRedirect("/d/"+name);
			} else {
				resp.sendRedirect("/d/"+name);
			}
		} else {
			resp.getWriter().println("domain does not exist !");
		}
	}
}
